//
//  LSZQualificationCertificationVC.m
//  JKFuYinProject
//
//  Created by 九酷 on 2018/8/29.
//  Copyright © 2018年 LC. All rights reserved.
//

#import "LSZQualificationCertificationVC.h"

@interface LSZQualificationCertificationVC ()<UITableViewDataSource,UITableViewDelegate,LDImagePickerDelegate,UITextFieldDelegate>
{
    NSArray * arrayTitle;
    NSArray * arrayHeaderTitle;
}
@property(nonatomic,strong) UITableView * tableViewQualification;
@property(nonatomic,strong) NSString * identityStr;//身份
@property(nonatomic,strong) NSString * identity_id;//身份id
@property(nonatomic,strong) LSZIdentityChooseManager * identityChooseManager;
@property(nonatomic,assign) NSInteger chooseRow;//选择的是哪一行
@property(nonatomic,strong) NSString * nameStr;//姓名
@property(nonatomic,strong) NSString * phoneStr;//联系方式
@property(nonatomic,strong) NSString * schoolStr;//学院

@property(nonatomic,strong) NSString * positiveID;//正面
@property(nonatomic,strong) NSString * reverseID;//反面
@property(nonatomic,strong) NSString * certificateID;//资质
@property(nonatomic,strong) NSString * positiveString;
@property(nonatomic,strong) NSString * reverseString;
@property(nonatomic,strong) NSString * certificateString;
@property(nonatomic,strong) NSString * status;//状态是否可以修改 2是审核过了
@end

@implementation LSZQualificationCertificationVC
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableViewQualification reloadData];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"资质认证";
    arrayTitle = @[@"姓   名:",@"联系方式:",@"居住地址:",@"所属教堂/教会/学院:",@"身份选择:"];
    arrayHeaderTitle = @[@"身份证正面",@"身份证反面",@"资质证书",@"申请留言:"];
    [self getIdentityChoose];
    [self getDataDic];
    [self.tableViewQualification registerClass:[LSZUploadDocumentsTableViewCell class] forCellReuseIdentifier:@"LSZUploadDocumentsTableViewCell"];
    [self.tableViewQualification registerClass:[LSZBasicInformationTableViewCell class] forCellReuseIdentifier:@"LSZBasicInformationTableViewCell"];
    [self.tableViewQualification registerClass:[LSZSaveAddressFootCell class] forHeaderFooterViewReuseIdentifier:@"LSZSaveAddressFootCell"];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return arrayHeaderTitle.count+1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return arrayTitle.count;
    }else{
        return 1;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0||indexPath.section == arrayHeaderTitle.count){
        CGFloat height = [LSZSpecialPackaging initWithReturnsthesizeOf:50 :5];
        return height;
    }else{
        CGFloat height = [LSZSpecialPackaging initWithReturnsthesizeOf:35 :2];
        return 141+height+33.78+12;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == arrayHeaderTitle.count) {
        return 110;
    }else{
        return 10;
    }
}
#pragma mark - iOS7下
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSString * resultStr = [textField.text stringByAppendingString:string];
    if (textField.tag == 1) {
        self.nameStr = resultStr;
    }
    if (textField.tag == 2) {
        self.phoneStr = resultStr;
    }
    if (textField.tag == 4) {
        self.schoolStr = resultStr;
    }
    return YES;
}
#pragma mark - iOS7上
- (void)textFieldEditChanged:(UITextField *)textField
{
    if (textField.tag == 1) {
        self.nameStr = textField.text;
    }
    if (textField.tag == 2) {
        self.phoneStr = textField.text;
    }
    if (textField.tag == 4) {
        self.schoolStr = textField.text;
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];//取消第一响应者
    return YES;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if (section == arrayHeaderTitle.count) {
        LSZSaveAddressFootCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"LSZSaveAddressFootCell"];
        if ([(self.status) isEqualToString:@"2"]) {
            [cell.buttonSave setTitle:@"审核通过,不能修改" forState:UIControlStateNormal];
            cell.buttonSave.userInteractionEnabled = NO;
            cell.buttonSave.backgroundColor = lightColor;
        }else{
            [cell.buttonSave setTitle:@"提 交" forState:UIControlStateNormal];
            cell.buttonSave.userInteractionEnabled = YES;
            cell.buttonSave.backgroundColor = redUIColor;
        }
        [cell.buttonSave addTarget:self action:@selector(clickSaveButton) forControlEvents:UIControlEventTouchUpInside];
        return cell;
    }else{
        UITableViewHeaderFooterView * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"cell"];
        if (!cell) {
            cell = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:@"cell"];
        }
        return cell;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0||indexPath.section == arrayHeaderTitle.count) {
        LSZBasicInformationTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZBasicInformationTableViewCell" forIndexPath:indexPath];
        cell.textFieldContent.delegate = self;
        cell.textFieldContent.tag = indexPath.row+1;
        if (indexPath.section == 0) {
            cell.labelTitleType.text = arrayTitle[indexPath.row];
        }else{
            cell.labelTitleType.text = arrayHeaderTitle[indexPath.section-1];
        }
        CGFloat height = [LSZSpecialPackaging initWithReturnsthesizeOf:18 :2];
        CGFloat A;
        if (ScreenWidth == 320) {
            A = 13;
        }else if(ScreenWidth == 375){
            A = 13.5;
        }else {
            A = 14;
        }
        CGFloat width = [LSZSpecialPackaging caculateWidthOfText:ScreenWidth height:height font:A :cell.labelTitleType.text]-10;
        CGRect rect = cell.labelTitleType.frame;
        rect.size.width = width;
        cell.labelTitleType.frame = rect;

        CGRect rectCont = cell.labelContent.frame;
        rectCont.origin.x = CGRectGetMaxX(cell.labelTitleType.frame);
        cell.labelContent.frame = rectCont;

        CGRect rectTextFieldCont = cell.textFieldContent.frame;
        rectTextFieldCont.origin.x = CGRectGetMaxX(cell.labelTitleType.frame);
        cell.textFieldContent.frame = rectTextFieldCont;

        if (indexPath.section == arrayHeaderTitle.count) {
            cell.textFieldContent.hidden = YES;//留言
            cell.labelContent.hidden = NO;
            if(self.IntroductionString.length == 0){
                cell.labelContent.text = @"请填写个人简介";
                cell.labelContent.textColor = lightColor;
            }else{
                cell.labelContent.text = self.IntroductionString;
                cell.labelContent.textColor = titleColorLSZ;
            }

        }else if(indexPath.row == 0&&indexPath.section == 0){
            cell.textFieldContent.hidden = NO;//姓名
            cell.labelContent.hidden = YES;
            if(self.nameStr.length == 0){
                cell.textFieldContent.placeholder = @"请输入姓名";
            }else{
                cell.textFieldContent.text = self.nameStr;
            }
        }else if(indexPath.row == 1){
            cell.textFieldContent.hidden = NO;//联系方式
            cell.labelContent.hidden = YES;
            if(self.phoneStr.length == 0){
                cell.textFieldContent.placeholder = @"请输入联系方式";
            }else{
                cell.textFieldContent.text = self.phoneStr;
            }
        }else if(indexPath.row == 2){
            cell.textFieldContent.hidden = YES;//居住地址
            cell.labelContent.hidden = NO;
            if (self.detailedAddressString.length == 0) {
                cell.labelContent.text = @"请选择居住地址";
                cell.labelContent.textColor = lightColor;
            }else{
                cell.labelContent.text = self.detailedAddressString;
                cell.labelContent.textColor = titleColorLSZ;
            }
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
        }else if(indexPath.row == 3){
            cell.textFieldContent.hidden = NO;//教堂教会
            cell.labelContent.hidden = YES;
            if(self.schoolStr.length == 0){
                cell.textFieldContent.placeholder = @"请输入教堂/教会/学校";
            }else{
                cell.textFieldContent.text = self.schoolStr;
            }
        }else if(indexPath.row == 4){
            cell.textFieldContent.hidden = YES;//身份选择
            cell.labelContent.hidden = NO;
            if(self.identityStr.length == 0){
                cell.labelContent.text = @"请选择身份";
                cell.labelContent.textColor = lightColor;
            }else{
                cell.labelContent.text = self.identityStr;
                cell.labelContent.textColor = titleColorLSZ;
            }
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; //显示最右边的箭头
        }
        [cell.textFieldContent addTarget:self action:@selector(textFieldEditChanged:)forControlEvents:UIControlEventEditingChanged];

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
        LSZUploadDocumentsTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"LSZUploadDocumentsTableViewCell" forIndexPath:indexPath];

        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"请上传%@: (信息仅用于身份验证,九酷福音保障您的信息安全)",arrayHeaderTitle[indexPath.section-1]]];

        NSRange range1 = [[string string] rangeOfString:[NSString stringWithFormat:@"请上传%@:",arrayHeaderTitle[indexPath.section-1]]];
        [string addAttribute:NSFontAttributeName value:FONT_(13.5) range:range1];
        NSRange range2 = [[string string] rangeOfString:@"(信息仅用于身份验证,九酷福音保障您的信息安全)"];
        [string addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:11.5] range:range2];
        [string addAttribute:NSForegroundColorAttributeName value:redUIColor range:range2];
        cell.labelType.attributedText = string;

        if(indexPath.section == 1 ){
            if ((NullStringjudgment(self.positiveID)).length == 0) {
                cell.imageViewOver.image = [UIImage imageNamed: arrayHeaderTitle[indexPath.section-1]];
            }else{
                [cell.imageViewOver sd_setImageWithURL:[NSURL URLWithString:self.positiveString] placeholderImage:[UIImage imageNamed:@""]];
            }
        }else if (indexPath.section == 2){
            if ((NullStringjudgment(self.reverseID)).length == 0) {
                cell.imageViewOver.image = [UIImage imageNamed: arrayHeaderTitle[indexPath.section-1]];
            }else{
                [cell.imageViewOver sd_setImageWithURL:[NSURL URLWithString:self.reverseString] placeholderImage:[UIImage imageNamed:@""]];
            }
        }else if (indexPath.section == 3){
            if ((NullStringjudgment(self.certificateID)).length == 0) {
                cell.imageViewOver.image = [UIImage imageNamed: arrayHeaderTitle[indexPath.section-1]];
            }else{
                [cell.imageViewOver sd_setImageWithURL:[NSURL URLWithString:self.certificateString] placeholderImage:[UIImage imageNamed:@""]];
            }
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0&&indexPath.row == 2) {
        LSZResidentialAddressVC * vc = [[LSZResidentialAddressVC alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (indexPath.section == 0&&indexPath.row == 4){
        [self selectTheId];
    }else if (indexPath.section == 1 || indexPath.section == 2||indexPath.section == 3){
        self.chooseRow = indexPath.section;
        [self chooseImageView];
    }else if(indexPath.section == 4){
        LSZNicknameVC * VC = [[LSZNicknameVC alloc]init];
        VC.whereFrom = [NSString stringWithFormat:@"%ld",(long)indexPath.row];
        [self.navigationController pushViewController:VC animated:YES];
    }
}
#pragma mark - 选择身份
-(void)selectTheId
{
    [self.view endEditing:YES];
    __weak typeof(self) weakSelf = self;
    NSMutableArray * ArrayData = [[NSMutableArray alloc]init];
    ArrayData = self.identityChooseManager.mutNameArray;
    DLPickerView *pickerView = [[DLPickerView alloc] initWithDataSource:ArrayData withSelectedItem:nil withSelectedBlock:^(id selectedItem){
        LSZBasicInformationTableViewCell * cell = (LSZBasicInformationTableViewCell *)[weakSelf.tableViewQualification cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4  inSection:0]];
        cell.labelContent.text = [NSString stringWithFormat:@"%@",selectedItem];
        self.identityStr = cell.labelContent.text;
        LSZIdentityChooseMg * mg = nil;
        for (int i = 0; i<self.identityChooseManager.arrayData.count; i++) {
            mg = self.identityChooseManager.arrayData[i];
            if ([mg.identity isEqualToString:selectedItem]) {
                self.identity_id = mg.id_id;
                break;
            }
        }
    }];
    [pickerView show];
}
-(void)chooseImageView
{
    __weak typeof(self) weakSelf = self;
    UIAlertController *actionSheetController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *showAllInfoAction = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf initWithPhoneFromThePhotoAlbum];
    }];
    UIAlertAction *pickAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf initWithPhoneTakingpictures];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [actionSheetController addAction:cancelAction];
    [actionSheetController addAction:pickAction];
    [actionSheetController addAction:showAllInfoAction];
    [weakSelf presentViewController:actionSheetController animated:YES completion:nil];
}
#pragma mark - 拍照
-(void)initWithPhoneTakingpictures
{
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //来源:相机
        sourceType = UIImagePickerControllerSourceTypeCamera;
        NSString * mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied) {
            [self initWithtring:@"摄像头访问受限,请打开摄像头允许拍摄!"];
            return;
        }
    }
    else {
        [self initWithtring:@"此设备没有摄像功能!"];
        return;
    }
    // 跳转到相机或相册页面
    LDImagePicker *imagePicker = [LDImagePicker sharedInstance];
    imagePicker.delegate = self;
    //设置宽高比scale来设置剪切框大小，剪切框宽度固定为屏幕宽度
    [imagePicker showImagePickerWithType:0   InViewController:self Scale:0.674];
}
#pragma mark - 从相册里面查找
-(void)initWithPhoneFromThePhotoAlbum
{
    NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    // 判断是否支持相机
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        //来源:相册//来自图库
        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied){
            //无权限
            [self initWithtring:@"照片访问受限,请允许app访问你的照片!"];
            return;
        }
    }
    else {
        //来自相册
        sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author == ALAuthorizationStatusRestricted || author == ALAuthorizationStatusDenied){
            //无权限
            [self initWithtring:@"照片访问受限,请允许app访问你的照片!"];
            return;
        }
    }
    // 跳转到相机或相册页面
    LDImagePicker *imagePicker = [LDImagePicker sharedInstance];
    imagePicker.delegate = self;
    //设置宽高比scale来设置剪切框大小，剪切框宽度固定为屏幕宽度
    [imagePicker showImagePickerWithType:1   InViewController:self Scale:0.674];
}
- (void)imagePicker:(LDImagePicker *)imagePicker didFinished:(UIImage *)editedImage{
    __weak typeof(self) weakSelf = self;
    UIImage *imagestr = editedImage;

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@".png"]];   // 保存文件的名称
    BOOL result = [UIImagePNGRepresentation(imagestr)writeToFile: filePath    atomically:YES]; // 保存成功会返回YES
    if(result == YES ){
        //需要在此处上传服务器
        [LSZRequestData toUploadPictures:@"/identity/upload" imageFile:imagestr filePath:filePath :^(BOOL isOk, NSString * str, NSDictionary * dic) {
            if(isOk == YES){
                NSArray * array = dic[@"data"];
                NSString * id_id = array[0][@"id"];
                NSString * url = array[0][@"url"];
                if(self.chooseRow == 1){
                    self.positiveID = id_id;
                    self.positiveString = url;
                }else if (self.chooseRow == 2){
                    self.reverseID = id_id;
                    self.reverseString = url;
                }else if (self.chooseRow == 3){
                    self.certificateID = id_id;
                    self.certificateString = url;
                }
                NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:self.chooseRow];
                [weakSelf.tableViewQualification reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
            }else{
                [self initWithtring:str];
            }
        }];
    }
}
#pragma mark - 保存按钮
-(void)clickSaveButton
{
    __weak typeof(self) weakSelf = self;
    if((NullStringjudgment(weakSelf.nameStr)).length == 0){
        [weakSelf initWithtring:@"请填写姓名!"];
        return;
    }
    if((NullStringjudgment(weakSelf.phoneStr)).length == 0){
        [weakSelf initWithtring:@"请填写联系方式!"];
        return;
    }
    if((NullStringjudgment(weakSelf.detailedAddressString)).length == 0){
        [weakSelf initWithtring:@"请填写居住地址!"];
        return;
    }
    if((NullStringjudgment(weakSelf.schoolStr)).length == 0){
        [weakSelf initWithtring:@"请填写所属教堂/教会/学院!"];
        return;
    }
    if((NullStringjudgment(weakSelf.identity_id)).length == 0){
        [weakSelf initWithtring:@"请选择身份!"];
        return;
    }
    if((NullStringjudgment(weakSelf.positiveID)).length == 0){
        [weakSelf initWithtring:@"请上传身份证正面!"];
        return;
    }
    if((NullStringjudgment(weakSelf.reverseID)).length == 0){
        [weakSelf initWithtring:@"请上传身份证反面!"];
        return;
    }
    if((NullStringjudgment(weakSelf.certificateID)).length == 0){
        [weakSelf initWithtring:@"请上传资质证书!"];
        return;
    }
    if((NullStringjudgment(weakSelf.IntroductionString)).length == 0){
        [weakSelf initWithtring:@"请填写个人简介!"];
        return;
    }
    [LSZRequestData submitQualificationCertificate:NullStringjudgment(weakSelf.nameStr) contact:NullStringjudgment(weakSelf.phoneStr) address:NullStringjudgment(weakSelf.detailedAddressString) mechanism:NullStringjudgment(weakSelf.schoolStr) identity:weakSelf.identity_id card:[NSString stringWithFormat:@"%@,%@",weakSelf.positiveID,weakSelf.reverseID] images:weakSelf.certificateID introduce:NullStringjudgment(weakSelf.IntroductionString) :^(BOOL isOk, NSString * string, NSDictionary * dic) {
        [weakSelf initWithtring:string];
        if (isOk == YES) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                // 刷新表格  和结束刷新
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
        }
    }];
}
#pragma mark - 查看是否有资质信息
-(void)getDataDic
{
    __weak typeof(self) weakSelf = self;
    [LSZRequestResolutionDic qualifiedUserApplicationResults:^(BOOL isOk, NSString * string, LSZQualificationApplicationResultsManager * manager) {
        if (isOk == YES) {
            weakSelf.nameStr         = manager.name;
            weakSelf.phoneStr        = manager.contact ;
            weakSelf.detailedAddressString  = manager.address;
            weakSelf.schoolStr       = manager.mechanism ;
            weakSelf.identityStr     = manager.identityStr;
            weakSelf.identity_id     = manager.identityID;
            weakSelf.positiveString  = manager.positive;
            weakSelf.positiveID      = manager.positiveID;
            weakSelf.reverseString   = manager.reverse;
            weakSelf.reverseID       = manager.reverseID;
            weakSelf.certificateString   = manager.images;
            weakSelf.certificateID   = manager.imagesID;
            weakSelf.IntroductionString  = manager.introduce ;
            weakSelf.status          = manager.status;
            [weakSelf.tableViewQualification reloadData];
        }
    }];
}
#pragma mark - 得到身份数据
-(void)getIdentityChoose
{
    __weak typeof(self) weakSelf = self;
    [LSZRequestResolutionDic initWithIdentityChoose:^(BOOL isOk, NSString * string, LSZIdentityChooseManager * manager) {
        if (isOk == YES) {
            weakSelf.identityChooseManager = manager;
        }else{
            [weakSelf initWithtring:string];
        }
    }];
}
-(UITableView *)tableViewQualification
{
    if (_tableViewQualification == nil) {
        _tableViewQualification = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStyleGrouped];
        _tableViewQualification.delegate = self;
        _tableViewQualification.dataSource = self;
        _tableViewQualification.separatorColor = divider;
        _tableViewQualification.estimatedRowHeight =0;
        _tableViewQualification.estimatedSectionFooterHeight =0;
        _tableViewQualification.estimatedSectionHeaderHeight =0;
        _tableViewQualification.separatorInset = UIEdgeInsetsMake(0, 20, 0, 20);
        [self.view addSubview:_tableViewQualification];
    }
    return _tableViewQualification;
}

@end
